package com.joysuch.wwyt.dynamicdata.service.impl;

import cn.zlg.common.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.joysuch.wwyt.core.enums.DeleteFlag;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.dynamicdata.entity.BaseDynamicData;
import com.joysuch.wwyt.dynamicdata.entity.dto.DynamicDataDto;
import com.joysuch.wwyt.dynamicdata.mapper.BaseDynamicDataMapper;
import com.joysuch.wwyt.dynamicdata.service.BaseDynamicDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jwk
 * @since 2021-11-26
 */
@Service
public class BaseDynamicDataServiceImpl extends ServiceImpl<BaseDynamicDataMapper, BaseDynamicData> implements BaseDynamicDataService {

    @Autowired
    private BaseDynamicDataMapper baseDynamicDataMapper;

    @Override
    public List<BaseDynamicData> findDataByBizId(Long bizId) {
        LambdaQueryWrapper<BaseDynamicData> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BaseDynamicData::getBizId, bizId);
        wrapper.eq(BaseDynamicData::getDeleteFlag, DeleteFlag.EFFECTIVE.getCode());
        wrapper.eq(BaseDynamicData::getTenentId, Context.getCurrentTenantId());
        wrapper.likeRight(BaseDynamicData::getOrgCode, Context.getCompanyCode());
        return super.list(wrapper);
    }

    @Override
    public List<DynamicDataDto> findDataByBizIds(Set<Long> bizIds) {
        List<DynamicDataDto> dataList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(bizIds)) {
            dataList = baseDynamicDataMapper.findDataByBizIds(bizIds, Context.getCurrentTenantId(), Context.getCompanyCode());
        }
        return dataList;
    }

    @Override
    public boolean saveOrUpdateDataBatch(List<BaseDynamicData> dataList, Set<Long> bizIds) {
        if (CollectionUtils.isNotEmpty(dataList)) {
            List<DynamicDataDto> data = findDataByBizIds(bizIds);
            Map<Long, List<DynamicDataDto>> dynamicDataMap = data.stream().collect(Collectors.groupingBy(DynamicDataDto::getBizId));
            dataList.forEach(each -> {
                if (dynamicDataMap.containsKey(each.getBizId())) {
                    List<DynamicDataDto> dynamicDataList = dynamicDataMap.get(each.getBizId());
                    Map<String, Long> nameIdMap = dynamicDataList.stream().collect(Collectors.toMap(DynamicDataDto::getFieldName, DynamicDataDto::getId));
                    if (nameIdMap.containsKey(each.getFieldName())) {
                        each.setId(nameIdMap.get(each.getFieldName()));
                    }
                }
            });
            return super.saveOrUpdateBatch(dataList);
        }
        return false;
    }

}
